﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.ServiceModel.DomainServices.Client.ApplicationServices;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Media;
using TheCollectiveNetwork.Web.Services;
using TheCollectiveNetwork.Classes.GlobalConstantsVariables;
using TheCollectiveNetwork.CustomControls;
using TCNDataAccessLayer;

namespace TheCollectiveNetwork.Views.Administration
{
    public partial class PersonDetailsWindow : ChildWindow
    {
        
        // Define Variables
        UserManagementContext _umc;
       
        public PersonDetailsWindow()
        {
            InitializeComponent();
            
        }

        /* ------------  Properties -------------- */
        public bool RecordModified {get; set;}        


        /* ------------  Public Functions -------------- */
        public void ShowPersonDetailsEdit(Guid pGuidID, UserManagementContext pumc)
        {
            // Variables
            Accounts_User_Details details;
                      

            // Set the data context
            _umc = pumc;

            // Clear the error panel
            PersonDetailsGrid_MessagePanel_MessageTextBlock.Text = string.Empty;
            PersonDetailsGrid_MessagePanel_CustomList.Clear();
            _umc.RejectChanges();

            //Check that the parent exists                      
            LoadOperation<DTOusername> loadOpParent = _umc.Load(_umc.GetAccounts_UsernameQuery(pGuidID));
            loadOpParent.Completed += (p_s, p_ea) =>
            {
                if (loadOpParent.TotalEntityCount == 1)
                {

                    // Get the data           
                    LoadOperation<Accounts_User_Details> loadOp = _umc.Load(_umc.Accounts_User_Details_ReadQuery(pGuidID));


                    // Once the load operation has completed set the datacontext of the grid
                    loadOp.Completed += (s, ea) =>
                    {
                        PersonSaveDetailsBtn.GuidID = pGuidID;
                        details = (Accounts_User_Details)loadOp.Entities.FirstOrDefault();

                        if (details == null)
                        {
                            // Load a new blank object
                            details = new Accounts_User_Details();
                            details.User_GUID = pGuidID;
                            PersonDetailsGrid.DataContext = details;
                            PersonSaveDetailsBtn.Mode = Constants.InsertMode;
                        }
                        else
                        {
                            // Load the record
                            PersonDetailsGrid.DataContext = details;
                            PersonSaveDetailsBtn.Mode = Constants.UpdateMode;
                        }

                        // Make the form visible
                        SwitchView(PersonDetailsBorder);

                    };
                }
                else
                {
                    // If the parent does not exist then switch to the does not exist message
                    SwitchView(PersonDetailsRecordNotExistBorder);
                }

                // Show the form
                this.Show();
            };
            
            
        }


        public void ShowPersonDetailsDelete(Guid pGuidID, UserManagementContext pumc)
        {            
            DTOusername dtouser;

            // Set the data context
            _umc = pumc;

            // Initialise Variables                      
            PersonDetailsDelete_Delete_Btn.GuidID = pGuidID;
            PersonDetailsDelete_MessagePanel_MessageTextBlock.Text = string.Empty;

            // Get the data           
            LoadOperation<DTOusername> loadOp = _umc.Load(_umc.GetAccounts_UsernameQuery(pGuidID));

            // Once the load operation has completed put the data on the screen and switch to the view
            loadOp.Completed += (s, ea) =>
            {
                if (loadOp.TotalEntityCount == 1)
                {
                    // Put the data on the screen
                    dtouser = (DTOusername)loadOp.Entities.FirstOrDefault();
                    PersonDetailsDeleteBorder.DataContext = dtouser;

                    // Switch the view
                    SwitchView(PersonDetailsDeleteBorder);
                }
                else
                {
                    // Switch the view
                    SwitchView(PersonDetailsRecordNotExistBorder);
                }

                // Show the form
                this.Show();

            };



        }

        /* ------------  Button Clicks -------------- */

      

        private void PersonSaveDetailsBtn_Click(object sender, EventArgs e)
        {
            GuidButton gbtn;
            Accounts_User_Details details;
            bool formblank;
            System.Windows.Documents.Run TextRun;
            SolidColorBrush scb_red;
            SolidColorBrush scb_green;


            // Get the sender button and data context, initialise variables
            gbtn = (GuidButton)sender;
            details = (Accounts_User_Details)PersonDetailsGrid.DataContext;
            formblank = false;
            scb_red = new SolidColorBrush(Colors.Red);
            scb_green = new SolidColorBrush(Colors.Green);            
            RecordModified = false;

            // Get the total length of the fields combined
            if (details.first_name == null && details.last_name == null && details.organisation == null && details.phone_number == null)
            {
                formblank = true;
            }

            // Clear the messages
            PersonDetailsGrid_MessagePanel_MessageTextBlock.Inlines.Clear();
            PersonDetailsGrid_MessagePanel_CustomList.Clear();

            if (details.HasValidationErrors)
            {
                //Write the message title           
                TextRun = new System.Windows.Documents.Run();
                TextRun.Text = "The following error(s) occurred;";
                TextRun.Foreground = scb_red;
                PersonDetailsGrid_MessagePanel_MessageTextBlock.HorizontalAlignment = HorizontalAlignment.Left;
                PersonDetailsGrid_MessagePanel_MessageTextBlock.Inlines.Add(TextRun);

                //Write the error list out                
                foreach (System.ComponentModel.DataAnnotations.ValidationResult vr in details.ValidationErrors)
                {
                    PersonDetailsGrid_MessagePanel_CustomList.Add(vr.ErrorMessage, scb_red);
                }

            }
            else
            {

                if (PersonSaveDetailsBtn.Mode == Constants.UpdateMode)
                {
                    // Remove the record if all fields are blank
                    if (formblank == true)
                    {
                        _umc.Accounts_User_Details.Remove(details);
                    }

                    // Update an existing record when submit has finished
                    var SubmitOp = _umc.SubmitChanges();
                    SubmitOp.Completed += (s, ea) =>
                    {
                        if (SubmitOp.HasError == false)
                        {
                            //Write success message            
                            TextRun = new System.Windows.Documents.Run();
                            TextRun.Text = "Record successfully saved";
                            TextRun.Foreground = scb_green;
                            PersonDetailsGrid_MessagePanel_MessageTextBlock.HorizontalAlignment = HorizontalAlignment.Center;
                            PersonDetailsGrid_MessagePanel_MessageTextBlock.Inlines.Add(TextRun);

                            // Set the record modified property, so the results can be refreshed
                            RecordModified = true;
                            
                           

                        }
                    };


                }
                else
                {
                    // Only add a record if fields contain data
                    if (formblank == false)
                    {
                        // Inserts a new record                              
                        _umc.Accounts_User_Details.Add(details);

                        var SubmitOp = _umc.SubmitChanges();
                        SubmitOp.Completed += (s, ea) =>
                        {
                            if (SubmitOp.HasError == false)
                            {
                                //Write success message            
                                TextRun = new System.Windows.Documents.Run();
                                TextRun.Text = "Record successfully saved";
                                TextRun.Foreground = scb_green;
                                PersonDetailsGrid_MessagePanel_MessageTextBlock.HorizontalAlignment = HorizontalAlignment.Center;
                                PersonDetailsGrid_MessagePanel_MessageTextBlock.Inlines.Add(TextRun);

                                // Set the record modified property, so the results can be refreshed
                                RecordModified = true;
                            }
                        };

                        // Change mode back to update incase user submits twice
                        PersonSaveDetailsBtn.Mode = Constants.UpdateMode;

                    }
                }


            }


        }

        private void PersonCloseDetailsBtn_Click(object sender, EventArgs e)
        {
            // Close form            
            this.Close();

        }


        private void PersonDetailsDelete_Close_Btn_Click(object sender, EventArgs e)
        {
            // Close form            
            this.Close();
        }

        private void PersonDetailsDelete_Delete_Btn_Click(object sender, EventArgs e)
        {
            DTOusername dtouser;
            System.Windows.Documents.Run TextRun;
            SolidColorBrush scb_red;
            SolidColorBrush scb_green;

            // Initialise variables
            scb_red = new SolidColorBrush(Colors.Red);
            scb_green = new SolidColorBrush(Colors.Green);
            PersonDetailsDelete_MessagePanel_MessageTextBlock.Inlines.Clear();


            // Delete the username, but check that it exists first
            dtouser = (DTOusername)PersonDetailsDeleteBorder.DataContext;           
            if (_umc.DTOAccountsUsers.Any(o => o.User_GUID == dtouser.User_GUID))
            {

                _umc.DTOusernames.Remove(dtouser);
                var SubmitOp = _umc.SubmitChanges();
                // Check for errors are the operation has completed

                SubmitOp.Completed += (s, ea) =>
                {
                    if (SubmitOp.HasError)
                    {
                        //Write the message                                                        
                        TextRun = new System.Windows.Documents.Run();
                        TextRun.Text = SubmitOp.Error.Message;
                        TextRun.Foreground = scb_red;
                        PersonDetailsDelete_MessagePanel_MessageTextBlock.HorizontalAlignment = HorizontalAlignment.Center;
                        PersonDetailsDelete_MessagePanel_MessageTextBlock.Inlines.Add(TextRun);


                        //Mark the error as handled to prevent silverlight throwing an exception
                        SubmitOp.MarkErrorAsHandled();
                    }
                    else
                    {
                        //Write success message            
                        TextRun = new System.Windows.Documents.Run();
                        TextRun.Text = "Record successfully deleted";
                        TextRun.Foreground = scb_green;
                        PersonDetailsDelete_MessagePanel_MessageTextBlock.HorizontalAlignment = HorizontalAlignment.Center;
                        PersonDetailsDelete_MessagePanel_MessageTextBlock.Inlines.Add(TextRun);

                        // Set the record modified property, so the results can be refreshed
                        RecordModified = true;
                    }

                };
            }
            else
            {
                // If the user doesn't exist, then advise user that it has been deleted.
                //Write the message                                                        
                TextRun = new System.Windows.Documents.Run();
                TextRun.Text = "Record does not exist.";
                TextRun.Foreground = scb_red;
                PersonDetailsDelete_MessagePanel_MessageTextBlock.HorizontalAlignment = HorizontalAlignment.Center;
                PersonDetailsDelete_MessagePanel_MessageTextBlock.Inlines.Add(TextRun);
            }

        }
       

        /* ------------ Private Functions -------------- */
        private void SwitchView(Border BorderCtrl)
        {
            
            // Switching logic
            if (BorderCtrl == PersonDetailsBorder)
            {
                // Open PersonDetailsBorder
                PersonDetailsBorder.Visibility = System.Windows.Visibility.Visible;

                // Close PersonDetailsDeleteBorder
                PersonDetailsDeleteBorder.Visibility = System.Windows.Visibility.Collapsed;
                PersonDetailsDeleteBorder.DataContext = null;

                // Close PersonDetailsRecordNotExistBorder  
                PersonDetailsRecordNotExistBorder.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if (BorderCtrl == PersonDetailsDeleteBorder)
            {
                // Set the background colour to light red
                LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255, 255, 239, 239));
                 
                // Open PersonDetailsDeleteBorder
                PersonDetailsDeleteBorder.Visibility = System.Windows.Visibility.Visible;

                // Close PersonDetailsBorder 
                PersonDetailsBorder.Visibility = System.Windows.Visibility.Collapsed;
                PersonDetailsGrid.DataContext = null;
                _umc.RejectChanges();

                // Close PersonDetailsRecordNotExistBorder  
                PersonDetailsRecordNotExistBorder.Visibility = System.Windows.Visibility.Collapsed;

            }
            else if (BorderCtrl == PersonDetailsRecordNotExistBorder)
            {
                // Open PersonDetailsRecordNotExistBorder 
                PersonDetailsRecordNotExistBorder.Visibility = System.Windows.Visibility.Visible;

                // Close PersonDetailsBorder 
                PersonDetailsBorder.Visibility = System.Windows.Visibility.Collapsed;
                PersonDetailsGrid.DataContext = null;
                _umc.RejectChanges();

                // Close PersonDetailsDeleteBorder
                PersonDetailsDeleteBorder.Visibility = System.Windows.Visibility.Collapsed;
                PersonDetailsDeleteBorder.DataContext = null;

            }
            else if (BorderCtrl == null)
            {
                // In the case of null close everything

                // Close PersonDetailsBorder
                PersonDetailsBorder.Visibility = System.Windows.Visibility.Collapsed;
                PersonDetailsGrid.DataContext = null;
                _umc.RejectChanges();

                // Close PersonDetailsDeleteBorder
                PersonDetailsDeleteBorder.Visibility = System.Windows.Visibility.Collapsed;

                // Close PersonDetailsRecordNotExistBorder  
                PersonDetailsRecordNotExistBorder.Visibility = System.Windows.Visibility.Collapsed;
            }

        }

    }
}

